package org.micode.demo.db.service.impl;

import org.micode.common.helper.I18nMsgHelper;
import org.micode.demo.db.dao.SysUserDao;
import org.micode.demo.db.dao.SysUserRoleDao;
import org.micode.demo.db.domain.dto.SysUserDTO;
import org.micode.demo.db.domain.dto.SysUserRoleDTO;
import org.micode.demo.db.domain.entity.SysUserDO;
import org.micode.demo.db.domain.query.SysUserQuery;
import org.micode.demo.db.service.DaoSysUserService;
import org.micode.common.domain.vo.EditObjVO;
import org.micode.common.utils.StringExtUtils;
import org.micode.libs.dao.base.BaseAllServiceImpl;
import org.micode.libs.dao.helper.IdHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户信息(sys_user) 服务实现类 
 * 
 * author: wutianbin
 */ 
@Service
@Slf4j
public class DaoSysUserServiceImpl
        extends BaseAllServiceImpl<Long, SysUserDTO, SysUserDO, SysUserQuery, SysUserDao>
        implements DaoSysUserService {

    @Autowired 
    private SysUserDao sysUserDao;

	@Autowired
	private SysUserRoleDao sysUserRoleDao;

	@Override
    protected SysUserDao getMyDao() {
        return sysUserDao;
    }

	@Transactional(rollbackFor = Throwable.class)
	@Override
	public SysUserDTO insert(SysUserDTO dto) {
		// 先添加
		SysUserDTO ret = super.insert(dto);

		// 然后授与角色
		if (null != ret && null != ret.getUserId()) {
			dto.setUserId(ret.getUserId());
			saveUserRoles(dto);
		}

		return ret;
	}

	private void saveUserRoles(SysUserDTO user) {
		try {
			List<Long> roles = user.getRoleIdList();
			if (null != roles && roles.size() > 0) {
				for (Long resId : roles) {
					SysUserRoleDTO userRole = new SysUserRoleDTO();
					userRole.setUserId(user.getUserId());
					userRole.setRoleId(resId);
					sysUserRoleDao.insert(userRole);
				}
			}
		} catch(Exception e) {
			log.error(I18nMsgHelper.get("fail.DaoSysUserServiceImpl-saveUserRoles.call"), e);
		}
	}

	@Transactional(rollbackFor = Throwable.class)
	@Override
	public int deleteByKeys(EditObjVO<List<Long>> delIds) {
		// 用新的删除方式，替换默认的 super.deleteByKeys(delIds)
		String ids = getKeysString(delIds.getWantEdit());

		int ret = 0;
		if (!StringExtUtils.isAnyEmpty(ids)) {
			ret = sysUserDao.updateDeleteForIds(ids,
					delIds.getUpdUser(), delIds.getUpdProg(), delIds.getUpdIp());
		}

		// 删除这些keys对应的权限
		deleteUserRoles(delIds.getWantEdit());

		return ret;
	}

	@Transactional(rollbackFor = Throwable.class)
	@Override
	public int update(SysUserDTO dto) {
		// 先更新
		int ret = super.update(dto);

		// 重置授权信息
		resetUserRolePerms(dto);

		return ret;
	}

	private void resetUserRolePerms(SysUserDTO user) {
		if (null == user || null == user.getUserId()) {
			return;
		}
		try {
			// 删除原来的授权
			sysUserRoleDao.deleteForUserId(user.getUserId());
			// 添加新的授权
			saveUserRoles(user);
		} catch(Exception e) {
			log.error(I18nMsgHelper.get("fail.DaoSysUserServiceImpl-resetUserRolePerms.call"), e);
		}
	}

	private void deleteUserRoles(List<Long> userIds) {
		try {
			if (null != userIds && userIds.size() > 0) {
				for (Long userId : userIds) {
					sysUserRoleDao.deleteForUserId(userId);
				}
			}
		} catch(Exception e) {
			log.error(I18nMsgHelper.get("fail.DaoSysUserServiceImpl-deleteUserRoles.call"), e);
		}
	}

	@Override
	public List<Long> listNotDefault(List<Long> userIds) {
		String idStr = IdHelper.getIdsStr(userIds);
		return sysUserDao.listUserIdNotDefault(idStr);
	}

	@Override
	public Integer updateUserPassword(SysUserDTO userDTO) {
		return sysUserDao.resetPwd(userDTO.getUserId(),
				userDTO.getPassword(),
				userDTO.getUpdUser(), userDTO.getUpdProg(), userDTO.getUpdIp());
	}

	@Override
	public SysUserDTO get(Long key) {
		SysUserDTO user =  super.get(key);
		if (null != user) {
			user.setRoleIdList(sysUserRoleDao.listRoleIdByUser(user.getUserId()));
		}
		return user;
	}

	@Override
	public SysUserDTO getOne(SysUserDTO example) {
		SysUserDTO user =  super.getOne(example);
		if (null != user) {
			user.setRoleIdList(sysUserRoleDao.listRoleIdByUser(user.getUserId()));
		}
		return user;
	}

}
